package com.pug.zixun.config.mvc;

import com.pug.zixun.config.interceptor.login.PassportLoginInterceptor;
import com.pug.zixun.config.interceptor.login.PassportLogoutInterceptor;
import com.pug.zixun.config.interceptor.repeat.RepeatSubmitInterceptor;
import org.passay.MessageResolver;
import org.passay.spring.SpringMessageResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2022/5/16$ 22:31$
 */
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Autowired
    private PassportLogoutInterceptor passportLogoutInterceptor;
    @Autowired
    private PassportLoginInterceptor passportLoginInterceptor;
    @Autowired
    private RepeatSubmitInterceptor repeatSubmitInterceptor;


    @Value("${file.staticPatternPath}")
    private String staticPatternPath;
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    /**
     * 默认解析器 其中locale表示默认语言
     * http://127.0.0.1:8877/admin/banner/saveupdate?lang=en_US
     * http://127.0.0.1:8877/admin/banner/saveupdate?lang=zh_CN
     *
     */
    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocaleResolver();
    }




    /**
     * 语言切换
     * @return
     */
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");
        return localeChangeInterceptor;
    }



    @Bean
    @Primary
    public MessageSource messageSource()  {
        ResourceBundleMessageSource rbms = new ResourceBundleMessageSource();
        rbms.setDefaultEncoding("UTF-8");
        rbms.setBasenames("i18n/messages");
        return rbms;
    }

    /**
     * 配置 Java Validation 使用国际化的消息资源
     * @return LocalValidatorFactoryBean
     */
    @Bean
    @Override
    public LocalValidatorFactoryBean getValidator() {
        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
        bean.setValidationMessageSource(messageSource());
        return bean;
    }

    /**
     * 配置 Passay 使用 Spring 的 MessageSource
     * @return MessageResolver
     */
    @Bean
    public MessageResolver messageResolver() {
        return new SpringMessageResolver(messageSource());
    }


    /**
     * 解决跨域问题
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
                .addMapping("/**")
                //.allowedOrigins("http://yyy.com", "http://xxx.com") //
                // 允许跨域的域名
                .allowedOriginPatterns("*") // 允许所有域
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                //.allowedMethods("*") // 允许任何方法（post、get等）
                .allowedHeaders("*") // 允许任何请求头
                .allowCredentials(true) // 允许证书、cookie
                .maxAge(3600L); // maxAge(3600)表明在3600秒内，不需要再发送预检验请求，可以缓存该结果
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //国际化切换
        registry.addInterceptor(localeChangeInterceptor());
        // 防止连续请求
        registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/admin/**");
        // 下线拦截器
        registry.addInterceptor(passportLogoutInterceptor).addPathPatterns("/admin/**")
                .excludePathPatterns("/admin/login/**","/admin/captcha");
        // 设置passportlogin的规则。以/admin开头的所有请求都要进行token校验
        registry.addInterceptor(passportLoginInterceptor).addPathPatterns("/admin/**")
                .excludePathPatterns("/admin/login/**","/admin/captcha");
    }


    /*
     * @Author 徐柯
     * @Description 静态资源拦截处理
     * @Date 20:11 2021/4/18
     * @Param [registry]
     * @return void
     *
     *
     * nginx
     * windows
     * server {
     *    location /resource {
     *       alias f:/uploadimages/
     *    }
     * }
     *
     * linux
     * server {
     *    location /resource {
     *       alias /www/uploadimages/
     *    }
     * }
     *
     *
     *  linux
     * server {
     *    location /resource {
     *       root /www/uploadimages
     *    }
     * }
     *
     * /resource  ---  /www/uploadimages/a.tx---- http://localhost/resource/a.txt
     * /resource  ---  /www/uploadimages/resource/a.tx---- http://localhost/resource/a.txt
     *
     * //window
     * staticPatternPath --- /resource ----- uploadFolder---f://uploadimages
     * // linux
     * staticPatternPath --- /resource ----- uploadFolder---/www/uploadimages
     **/
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(staticPatternPath).addResourceLocations("file:" + uploadFolder);
    }

}
